package org.client.iot.ui.device;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import org.client.iot.R;
import org.client.iot.databinding.ActivityMonitorDataBinding;
import org.client.iot.ui.device.monitorDataFragment.MonitorChartFragment;
import org.client.iot.ui.device.monitorDataFragment.MonitorDataListFragment;
import org.tzw.template.base.BaseActivity;
import org.tzw.template.base.BaseFragment;

public class MonitorDataActivity extends BaseActivity<ActivityMonitorDataBinding> {
    private String currentStartDate = "2024-08-28";
    private String currentEndDate = "2024-09-01";
    private BaseFragment<?> currentFragment;

    @Override
    protected void initView() {
        setSupportActionBar(mRoot.toolbarMonitorData.toolbarPageHead);
        mRoot.toolbarMonitorData.textViewTitle.setText(getString(R.string.monitor_toolbar_title));
        switchToChartFragment();
    }

    @Override
    protected void initListener() {
        mRoot.textViewPicToText.setOnClickListener(v -> toggleFragments());
        mRoot.toolbarMonitorData.imgBack.setOnClickListener(v -> finish());
    }

    private void toggleFragments() {
        if (currentFragment instanceof MonitorChartFragment) {
            switchToListFragment();
        } else {
            switchToChartFragment();
        }
    }

    private void switchToChartFragment() {
        currentFragment = MonitorChartFragment.newInstance(currentStartDate, currentEndDate);
        replaceFragment(currentFragment);
    }

    private void switchToListFragment() {
        currentFragment = MonitorDataListFragment.newInstance(currentStartDate, currentEndDate);
        replaceFragment(currentFragment);
    }

    private void replaceFragment(BaseFragment<?> fragment) {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.frame_layout_monitor_container, fragment)
                .commit();
    }

    // 更新当前Fragment时间的方法
    public void updateTimeRange(String newStart, String newEnd) {
        currentStartDate = newStart;
        currentEndDate = newEnd;
        if (currentFragment instanceof TimeRangeUpdatable) {
            ((TimeRangeUpdatable) currentFragment).updateTimeRange(newStart, newEnd);
        }
    }

    public interface TimeRangeUpdatable {
        void updateTimeRange(String startDate, String endDate);
    }
}

